<template>
  <div class="pb50">
    <el-form
      size="small"
      ref="form"
      :model="form"
      label-width="150px"
      :rules="rules"
    >
      <!--基础-->
      <Basic :form="form"></Basic>
      <!--字段-->
      <Fields :form="form"></Fields>
    </el-form>

    <!--提交-->
    <div class="common-button-wrapper">
      <el-button size="small" @click="cancelFunc">取消</el-button>
      <el-button
        size="small"
        type="primary"
        @click="onSubmit"
        :loading="loading"
        >提交</el-button
      >
    </div>
  </div>
</template>
<script>
import TableApi from "@/api/plus/table.js";
import Basic from "./part/Basic.vue";
import Fields from "./part/Fields.vue";
export default {
  components: {
    /*基础设置*/
    Basic,
    /*活动商品*/
    Fields,
  },
  data() {
    const validatorTableData = (rule, value, callback) => {
      let flag = false;
      if (this.form.tableData && this.form.tableData.length > 0) {
        for (let i = 0; i < this.form.tableData.length; i++) {
          let v = this.form.tableData[i];
          if (!v.name) {
            flag = true;
            callback(new Error("名称必填！！！"));
            break;
          }
          if (
            (v.type == "radio" ||
              v.type == "radio-group" ||
              v.type == "select") &&
            !v.selectValue
          ) {
            flag = true;
            break;
          }
        }
        if (flag) {
          callback(new Error("请填写完整！！！"));
        }
      } else {
        callback(new Error("字段必添加！！！"));
        return;
      }
      callback();
    };
    return {
      /*表单对象*/
      form: {
        name: "",
        /*默认排序*/
        sort: 100,
        /*商品源数据*/
        tableData: [],
      },
      rules: {
        tableData: [
          { validator: validatorTableData, required: true, trigger: "change" },
        ],
      },
      /*是否正在加载*/
      loading: false,
    };
  },
  created() {},
  methods: {
    /*提交表单*/
    onSubmit() {
      let self = this;
      self.$refs.form.validate((valid) => {
        if (valid) {
          let params = {};
          params.fields = self.form.tableData;
          params.name = self.form.name;
          params.sort = self.form.sort;
          self.loading = true;
          TableApi.add(params, true)
            .then((res) => {
              self.loading = false;
              ElMessage({
                message: "恭喜你，添加成功",
                type: "success",
              });
              self.cancelFunc();
            })
            .catch((error) => {
              self.loading = false;
            });
        }
      });
    },
    /*取消*/
    cancelFunc() {
      this.$router.back(-1);
    },
  },
};
</script>
<style lang="scss" scoped></style>
